'use client';

import { useState, useEffect } from 'react';
import GlassCard from '@/components/ui/GlassCard';
import GlassButton from '@/components/ui/GlassButton';
import GlassInput from '@/components/ui/GlassInput';
import PasswordInput from '@/components/ui/PasswordInput';
import { User, Settings, Save, Edit } from 'lucide-react';
import toast from 'react-hot-toast';
import { useAuthStore } from '@/store/authStore';
import { authApi } from '@/lib/api';

interface UserPreferences {
  preferred_llm_model?: string;
  preferred_embedding_model?: string;
  temperature?: number;
  max_tokens?: number;
}

export default function ProfilePage() {
  const { user, setUser } = useAuthStore();
  const [loading, setLoading] = useState(false);
  const [models, setModels] = useState<any[]>([]);
  const [preferences, setPreferences] = useState<UserPreferences>({
    temperature: 0.7,
    max_tokens: 2000,
  });
  
  // 个人信息编辑
  const [editingProfile, setEditingProfile] = useState(false);
  const [profileForm, setProfileForm] = useState({
    email: '',
    full_name: '',
    department: '',
  });
  
  // 密码修改
  const [showPasswordChange, setShowPasswordChange] = useState(false);
  const [passwordForm, setPasswordForm] = useState({
    currentPassword: '',
    newPassword: '',
    confirmPassword: '',
  });

  useEffect(() => {
    loadModels();
    loadPreferences();
    if (user) {
      setProfileForm({
        email: user.email || '',
        full_name: user.full_name || '',
        department: user.department || '',
      });
    }
  }, [user]);

  const loadModels = async () => {
    try {
      const { modelsApi } = await import('@/lib/api');
      const response = await modelsApi.list();
      setModels(response.models || []);
    } catch (error: any) {
      console.error('加载模型列表失败:', error);
    }
  };

  const loadPreferences = async () => {
    try {
      const saved = localStorage.getItem('user_preferences');
      if (saved) {
        setPreferences(JSON.parse(saved));
      }
    } catch (error: any) {
      console.error('加载偏好设置失败:', error);
    }
  };

  const handleSave = async () => {
    try {
      setLoading(true);
      // 保存到 localStorage（用户个人设置）
      localStorage.setItem('user_preferences', JSON.stringify(preferences));
      toast.success('✅ 个人偏好已保存！仅对您自己生效');
    } catch (error: any) {
      toast.error('保存失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  const handleProfileSave = async () => {
    if (!user) return;
    
    try {
      setLoading(true);
      // 调用后端API更新用户信息
      // 注意：需要添加usersApi.updateProfile方法
      const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3301/api'}/users/${user.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('access_token')}`
        },
        body: JSON.stringify(profileForm)
      });
      
      if (!response.ok) throw new Error('更新失败');
      
      // 重新获取用户信息
      const updatedUser = await authApi.getCurrentUser();
      setUser(updatedUser);
      
      toast.success('✅ 个人信息已更新');
      setEditingProfile(false);
    } catch (error: any) {
      toast.error('更新失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  const handlePasswordChange = async () => {
    if (!user) return;
    
    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      toast.error('两次输入的密码不一致');
      return;
    }
    
    if (passwordForm.newPassword.length < 6) {
      toast.error('密码长度至少6位');
      return;
    }
    
    try {
      setLoading(true);
      const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3301/api'}/users/${user.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${localStorage.getItem('access_token')}`
        },
        body: JSON.stringify({
          password: passwordForm.newPassword
        })
      });
      
      if (!response.ok) throw new Error('修改失败');
      
      toast.success('✅ 密码已修改');
      setShowPasswordChange(false);
      setPasswordForm({
        currentPassword: '',
        newPassword: '',
        confirmPassword: '',
      });
    } catch (error: any) {
      toast.error('修改失败: ' + (error.message || '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  const getLlmModels = () => {
    return models.filter(m =>
      !m.name.includes('embed') &&
      !m.name.includes('embedding')
    );
  };

  const getEmbeddingModels = () => {
    const embedModels = models.filter(m =>
      m.name.includes('embed') ||
      m.name.includes('embedding')
    );
    return embedModels.length > 0 ? embedModels : models;
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4 mb-6">
        <div className="p-3 rounded-2xl bg-gradient-to-br from-indigo-500/20 to-purple-500/20 backdrop-blur-md">
          <User className="h-8 w-8 text-indigo-600 dark:text-indigo-400" />
        </div>
        <div>
          <h1 className="text-3xl font-extrabold">
            <span className="bg-gradient-to-r from-indigo-600 via-purple-600 to-pink-600 bg-clip-text text-transparent dark:from-indigo-300 dark:via-purple-300 dark:to-pink-300">
              个人设置
            </span>
          </h1>
          <p className="text-gray-600 dark:text-white/60 mt-1">
            配置您的个人偏好，不影响其他用户
          </p>
        </div>
      </div>

      {/* User Info */}
      <GlassCard className="p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-bold text-gray-900 dark:text-white flex items-center gap-2">
            <User className="h-5 w-5 text-indigo-500" />
            账户信息
          </h2>
          <GlassButton
            onClick={() => setEditingProfile(!editingProfile)}
            variant="secondary"
            size="sm"
          >
            <Edit className="h-4 w-4 mr-2" />
            {editingProfile ? '取消编辑' : '编辑'}
          </GlassButton>
        </div>

        {editingProfile ? (
          <div className="space-y-4">
            <GlassInput
              label="邮箱"
              type="email"
              value={profileForm.email}
              onChange={(e) => setProfileForm({ ...profileForm, email: e.target.value })}
              placeholder="your@email.com"
            />
            <GlassInput
              label="全名"
              value={profileForm.full_name}
              onChange={(e) => setProfileForm({ ...profileForm, full_name: e.target.value })}
              placeholder="张三"
            />
            <GlassInput
              label="部门"
              value={profileForm.department}
              onChange={(e) => setProfileForm({ ...profileForm, department: e.target.value })}
              placeholder="技术部"
            />
            <GlassButton
              onClick={handleProfileSave}
              variant="primary"
              loading={loading}
              disabled={loading}
            >
              <Save className="h-4 w-4 mr-2" />
              保存修改
            </GlassButton>
          </div>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* 左列 */}
            <div className="space-y-4">
              <div className="bg-gradient-to-br from-indigo-50 to-purple-50 dark:from-indigo-500/10 dark:to-purple-500/10 rounded-xl p-4 border border-indigo-200/40 dark:border-indigo-500/30">
                <div className="text-xs text-gray-500 dark:text-white/50 mb-1">用户名</div>
                <div className="text-lg font-bold text-gray-900 dark:text-white">{user?.username}</div>
              </div>
              
              <div className="bg-gradient-to-br from-blue-50 to-cyan-50 dark:from-blue-500/10 dark:to-cyan-500/10 rounded-xl p-4 border border-blue-200/40 dark:border-blue-500/30">
                <div className="text-xs text-gray-500 dark:text-white/50 mb-1">邮箱</div>
                <div className="text-sm font-medium text-gray-900 dark:text-white break-all">
                  {user?.email || <span className="text-gray-400 dark:text-white/40">未设置</span>}
                </div>
              </div>
              
              <div className="bg-gradient-to-br from-emerald-50 to-teal-50 dark:from-emerald-500/10 dark:to-teal-500/10 rounded-xl p-4 border border-emerald-200/40 dark:border-emerald-500/30">
                <div className="text-xs text-gray-500 dark:text-white/50 mb-1">全名</div>
                <div className="text-sm font-medium text-gray-900 dark:text-white">
                  {user?.full_name || <span className="text-gray-400 dark:text-white/40">未设置</span>}
                </div>
              </div>
            </div>
            
            {/* 右列 */}
            <div className="space-y-4">
              <div className="bg-gradient-to-br from-orange-50 to-amber-50 dark:from-orange-500/10 dark:to-amber-500/10 rounded-xl p-4 border border-orange-200/40 dark:border-orange-500/30">
                <div className="text-xs text-gray-500 dark:text-white/50 mb-1">部门</div>
                <div className="text-sm font-medium text-gray-900 dark:text-white">
                  {user?.department || <span className="text-gray-400 dark:text-white/40">未设置</span>}
                </div>
              </div>
              
              <div className="bg-gradient-to-br from-pink-50 to-rose-50 dark:from-pink-500/10 dark:to-rose-500/10 rounded-xl p-4 border border-pink-200/40 dark:border-pink-500/30">
                <div className="text-xs text-gray-500 dark:text-white/50 mb-2">角色</div>
                <span className={`inline-flex px-4 py-2 rounded-full text-sm font-bold shadow-lg ${
                  user?.role === 'admin' 
                    ? 'bg-gradient-to-r from-red-500 to-pink-500 text-white' 
                    : user?.role === 'manager'
                    ? 'bg-gradient-to-r from-blue-500 to-cyan-500 text-white'
                    : 'bg-gradient-to-r from-green-500 to-emerald-500 text-white'
                }`}>
                  {user?.role === 'admin' ? '管理员' : user?.role === 'manager' ? '经理' : '普通用户'}
                </span>
              </div>
            </div>
          </div>
        )}

        {/* 密码修改 */}
        <div className="mt-6 pt-6 border-t border-gray-200/40 dark:border-white/20">
          {!showPasswordChange ? (
            <GlassButton
              onClick={() => setShowPasswordChange(true)}
              variant="secondary"
              size="sm"
            >
              修改密码
            </GlassButton>
          ) : (
            <div className="space-y-4">
              <h3 className="text-lg font-semibold text-gray-900 dark:text-white">修改密码</h3>
              <PasswordInput
                label="新密码"
                value={passwordForm.newPassword}
                onChange={(e) => setPasswordForm({ ...passwordForm, newPassword: e.target.value })}
                placeholder="输入新密码"
              />
              <PasswordInput
                label="确认密码"
                value={passwordForm.confirmPassword}
                onChange={(e) => setPasswordForm({ ...passwordForm, confirmPassword: e.target.value })}
                placeholder="再次输入新密码"
              />
              <div className="flex gap-3">
                <GlassButton
                  onClick={() => {
                    setShowPasswordChange(false);
                    setPasswordForm({ currentPassword: '', newPassword: '', confirmPassword: '' });
                  }}
                  variant="secondary"
                  className="flex-1"
                >
                  取消
                </GlassButton>
                <GlassButton
                  onClick={handlePasswordChange}
                  variant="primary"
                  loading={loading}
                  disabled={loading}
                  className="flex-1"
                >
                  确认修改
                </GlassButton>
              </div>
            </div>
          )}
        </div>
      </GlassCard>

      {/* Model Preferences */}
      <GlassCard className="p-6">
        <h2 className="text-xl font-bold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
          <Settings className="h-5 w-5 text-indigo-500" />
          模型偏好
        </h2>
        <p className="text-sm text-amber-600 dark:text-amber-400 mb-4 p-3 bg-amber-50 dark:bg-amber-500/10 rounded-lg border border-amber-200 dark:border-amber-500/30">
          ⚡ 提示：这些设置只对您自己生效，不会影响其他用户或系统全局配置
        </p>

        <div className="space-y-6">
          {/* LLM Model */}
          <div>
            <label className="block text-sm font-semibold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent dark:from-indigo-400 dark:to-purple-400 mb-2">
              首选 LLM 模型
            </label>
            <select
              value={preferences.preferred_llm_model || ''}
              onChange={(e) => setPreferences({ ...preferences, preferred_llm_model: e.target.value })}
              className="w-full px-4 py-3 bg-white/60 dark:bg-white/10 backdrop-blur-md border border-gray-300/40 dark:border-white/20 rounded-lg text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
            >
              <option value="">使用系统默认</option>
              {getLlmModels().map((model) => (
                <option key={model.name} value={model.name} className="bg-white dark:bg-gray-800">
                  {model.name}
                </option>
              ))}
            </select>
            <p className="text-xs text-gray-500 dark:text-white/50 mt-1">
              RAG问答时优先使用此模型
            </p>
          </div>

          {/* Embedding Model */}
          <div>
            <label className="block text-sm font-semibold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent dark:from-indigo-400 dark:to-purple-400 mb-2">
              首选 Embedding 模型
            </label>
            <select
              value={preferences.preferred_embedding_model || ''}
              onChange={(e) => setPreferences({ ...preferences, preferred_embedding_model: e.target.value })}
              className="w-full px-4 py-3 bg-white/60 dark:bg-white/10 backdrop-blur-md border border-gray-300/40 dark:border-white/20 rounded-lg text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
            >
              <option value="">使用系统默认</option>
              {getEmbeddingModels().map((model) => (
                <option key={model.name} value={model.name} className="bg-white dark:bg-gray-800">
                  {model.name}
                </option>
              ))}
            </select>
            <p className="text-xs text-gray-500 dark:text-white/50 mt-1">
              文档向量化时优先使用此模型
            </p>
          </div>

          {/* Temperature */}
          <div>
            <label className="block text-sm font-semibold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent dark:from-indigo-400 dark:to-purple-400 mb-2">
              Temperature（创造性）
            </label>
            <div className="flex items-center gap-4">
              <input
                type="range"
                min="0"
                max="1"
                step="0.1"
                value={preferences.temperature || 0.7}
                onChange={(e) => setPreferences({ ...preferences, temperature: parseFloat(e.target.value) })}
                className="flex-1"
              />
              <span className="text-lg font-bold text-indigo-600 dark:text-indigo-400 w-12">
                {preferences.temperature?.toFixed(1)}
              </span>
            </div>
            <p className="text-xs text-gray-500 dark:text-white/50 mt-1">
              值越高，回答越有创造性；值越低，回答越严谨
            </p>
          </div>

          {/* Max Tokens */}
          <div>
            <label className="block text-sm font-semibold bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent dark:from-indigo-400 dark:to-purple-400 mb-2">
              最大输出长度（Max Tokens）
            </label>
            <GlassInput
              type="number"
              min="100"
              max="8000"
              step="100"
              value={preferences.max_tokens || 2000}
              onChange={(e) => setPreferences({ ...preferences, max_tokens: parseInt(e.target.value) })}
            />
            <p className="text-xs text-gray-500 dark:text-white/50 mt-1">
              控制 AI 回答的最大长度
            </p>
          </div>
        </div>

        {/* Save Button */}
        <div className="mt-6 flex justify-end">
          <GlassButton
            onClick={handleSave}
            loading={loading}
            disabled={loading}
            variant="primary"
            size="lg"
          >
            <Save className="mr-2 h-5 w-5" />
            保存偏好设置
          </GlassButton>
        </div>
      </GlassCard>

      {/* Info Card */}
      <GlassCard className="p-6 bg-gradient-to-br from-blue-50/50 to-indigo-50/50 dark:from-blue-900/10 dark:to-indigo-900/10 border border-blue-200/40 dark:border-blue-500/30">
        <h3 className="text-lg font-bold text-blue-900 dark:text-blue-300 mb-2">
          💡 关于个人设置
        </h3>
        <ul className="space-y-2 text-sm text-blue-800 dark:text-blue-200">
          <li className="flex items-start gap-2">
            <span className="text-blue-500 dark:text-blue-400 mt-0.5">•</span>
            <span>您的偏好设置仅保存在您的浏览器中，不会影响其他用户</span>
          </li>
          <li className="flex items-start gap-2">
            <span className="text-blue-500 dark:text-blue-400 mt-0.5">•</span>
            <span>如果未设置模型偏好，系统会自动使用管理员配置的全局模型</span>
          </li>
          <li className="flex items-start gap-2">
            <span className="text-blue-500 dark:text-blue-400 mt-0.5">•</span>
            <span>更换浏览器或清除缓存后，需要重新设置您的偏好</span>
          </li>
        </ul>
      </GlassCard>
    </div>
  );
}

